<template>
  <div class="purchase-history">
    <div class="history-head">
      <van-tabs v-model="activeTab">
        <van-tab title="全部"></van-tab>
        <van-tab title="待收货"></van-tab>
        <van-tab title="已完成"></van-tab>
      </van-tabs>
    </div>
    <div class="history-content">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-if="tabData[activeTab].orders.length"
          v-model="tabData[activeTab].loading"
          :finished="tabData[activeTab].finished"
          :immediate-check="false"
          offset="30"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div class="order-list">
            <div
              class="order-item"
              v-for="order in tabData[activeTab].orders"
              :key="order.id"
            >
              <div class="order-header">
                <div class="order-time">订单时间: {{ formatDateTime(order.createTime) }}</div>
                <div class="order-status" :class="getStatusClass(order.status)">
                  {{ getStatusText(order.status) }}
                </div>
              </div>
            <div class="order-info">
              <div class="product-image">
                <img :src="order.productImage" alt="商品图片" />
              </div>
              <div class="product-details">
                <div class="product-name">{{ order.productName }}</div>
                <div class="product-points" v-if="order.purchaseMethod === '1'">消耗积分: {{ order.points }} 积分</div>
                <div class="product-points" v-else-if="order.purchaseMethod === '2'">现金购买: {{ formatAmount(order.points) }} 元</div>
                <div class="product-points" v-else>消耗积分: {{ order.points }} 积分</div>
                <div class="order-number">订单号: {{ order.orderNo }}</div>
                <div class="order-number">学生姓名: {{ order.studentName }}</div>
                <div class="purchase-method">购买方式: {{ getPurchaseMethodText(order.purchaseMethod) }}</div>
              </div>
            </div>
              <div class="order-actions">
                <van-button
                  size="small"
                  plain
                  type="primary"
                  @click="showOrderDetail(order)"
                >
                  查看详情
                </van-button>
              </div>
            </div>
          </div>
        </van-list>
        <div class="nodata" v-if="!tabData[activeTab].orders.length">
          <van-empty description="暂无购买记录" />
        </div>
      </van-pull-refresh>
    </div>

    <!-- 退货原因输入弹窗 -->
    <van-popup
      v-model="showCancelDialog"
      position="bottom"
      closeable
      round
      :style="{ height: '50%' }"
    >
      <div class="cancel-dialog">
        <div class="dialog-header">
          <h3>取消兑换</h3>
        </div>
        <div class="dialog-content">
          <div class="input-section">
            <div class="input-label">请输入取消兑换的原因：</div>
            <van-field
              v-model="returnReason"
              type="textarea"
              rows="4"
              placeholder="请输入取消兑换的原因"
              maxlength="200"
              show-word-limit
            />
          </div>
        </div>
        <div class="dialog-actions">

          <van-button
            type="primary"
            size="large"
            @click="submitCancelExchange"
            :disabled="!returnReason.trim()"
          >
            确定
          </van-button>
        </div>
      </div>
    </van-popup>

    <!-- 订单详情弹窗 -->
    <van-popup
      v-model="showDetail"
      position="bottom"
      closeable
      round
      :style="{ height: '80%' }"
    >
      <div class="order-detail">
        <div class="detail-header">
          <h3>订单详情</h3>
        </div>
        <div class="detail-content">
          <div class="detail-section">
            <div class="section-title">商品信息</div>
            <div class="product-info">
              <div class="product-image">
                <img :src="currentOrder.productImage" alt="商品图片" />
              </div>
              <div class="product-details">
                <div class="product-name">{{ currentOrder.productName }}</div>
                <div class="product-points" v-if="currentOrder.purchaseMethod === '1'">消耗积分: {{ currentOrder.points }} 积分</div>
                <div class="product-points" v-else-if="currentOrder.purchaseMethod === '2'">现金购买: {{ formatAmount(currentOrder.points) }} 元</div>
                <div class="product-points" v-else>消耗积分: {{ currentOrder.points }} 积分</div>
              </div>
            </div>
          </div>

          <div class="detail-section">
            <div class="section-title">订单信息</div>
            <div class="order-info-list">
              <div class="info-item">
                <span class="label">订单号:</span>
                <span class="value">{{ currentOrder.orderNo }}</span>
              </div>
              <div class="info-item">
                <span class="label">下单时间:</span>
                <span class="value">{{ formatDateTime(currentOrder.createTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">订单状态:</span>
                <span class="value" :class="getStatusClass(currentOrder.status)">
                  {{ getStatusText(currentOrder.status) }}
                </span>
              </div>
              <div class="info-item">
                <span class="label">学生姓名:</span>
                 <span class="value">{{ currentOrder.studentName }}</span>
              </div>
              <div class="info-item">
                <span class="label">购买方式:</span>
                <span class="value">{{ getPurchaseMethodText(currentOrder.purchaseMethod) }}</span>
              </div>
            </div>
          </div>

          <div class="detail-section" v-if="currentOrder.description">
            <div class="section-title">商品描述</div>
            <div class="product-description">
              {{ currentOrder.description }}
            </div>
          </div>
        </div>

        <div class="detail-actions" v-if="currentOrder.status === '1'">
          <van-button
            type="primary"
            size="large"
            @click="confirmReceipt(currentOrder)"
          >
            确认收货
          </van-button>
          <van-button
            type="default"
            size="large"
            @click="cancelExchange(currentOrder)"
            style="margin-top: 10px;"
          >
            取消兑换
          </van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { Tab, Tabs, Button, Toast, Popup, Loading, PullRefresh, Dialog, Field, List, Empty } from 'vant'
import api from '@/api'

export default {
  name: 'PurchaseHistory',
  components: {
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Button.name]: Button,
    [Popup.name]: Popup,
    [PullRefresh.name]: PullRefresh,
    [Field.name]: Field,
    [List.name]: List,
    [Empty.name]: Empty
  },
  data() {
    return {
      activeTab: 0,
      showDetail: false,
      showCancelDialog: false,
      currentOrder: {},
      currentStudent: null,
      allOrders: [],
      loading: false,
      refreshing: false,
      returnReason: '',
      selectedOrderId: null,
      // 分页相关数据
      currentPage: 1,
      pageSize: 10,
      hasMore: true,
      loadingMore: false,
      // 各标签页的数据
      tabData: {
        0: { orders: [], page: 1, hasMore: true, loading: false, finished: false }, // 全部
        1: { orders: [], page: 1, hasMore: true, loading: false, finished: false }, // 待收货
        2: { orders: [], page: 1, hasMore: true, loading: false, finished: false }  // 已完成
      }
    }
  },
  created() {
    // 获取路由参数中的学生信息
    this.currentStudent = this.$route.params.studentInfo || null
    // 同时从 localStorage 获取学生信息作为备份
    const storedStudent = localStorage.getItem('currentStudentInfo')
    if (storedStudent) {
      try {
        this.currentStudent = JSON.parse(storedStudent)
      } catch (e) {
        console.error('解析存储的学生信息失败:', e)
      }
    }

    // 进入页面时加载购买历史数据
    this.loadPurchaseHistory()
  },
  beforeRouteLeave(to, from, next) {
    // 如果返回到积分商城页面，设置标记
    if (to.name === 'pointsMall') {
      sessionStorage.setItem('fromPurchaseHistory', 'true')
      console.log('设置从购买记录页面返回标记')
    }
    next()
  },
  computed: {
    pendingOrders() {
      return this.allOrders.filter(order => order.status === "1")
    },
    completedOrders() {
      return this.allOrders.filter(order => order.status === "3")
    }
  },
  watch: {
    activeTab() {
      // 当标签切换时重置分页状态并重新加载数据
      const currentTabData = this.tabData[this.activeTab]
      currentTabData.page = 1
      currentTabData.orders = []
      currentTabData.hasMore = true
      currentTabData.loading = false
      currentTabData.finished = false
      this.loadPurchaseHistory()
    }
  },
  methods: {
    // 下拉刷新
    onRefresh() {
      this.refreshing = true
      this.loadPurchaseHistory()
      setTimeout(() => {
        this.refreshing = false
      }, 1000)
    },

    // 格式化时间显示为年月日时分秒
    formatDateTime(dateTime) {
      if (!dateTime) return ''

      const date = new Date(dateTime)
      if (isNaN(date.getTime())) return dateTime

      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    // 下拉加载更多
    onLoad() {
      const currentTabData = this.tabData[this.activeTab]
      if (!currentTabData.hasMore) {
        currentTabData.loading = false
        currentTabData.finished = true
        return
      }
      currentTabData.page = currentTabData.page + 1
      this.loadPurchaseHistory()
    },

    // 加载购买历史数据
    async loadPurchaseHistory() {
      if (!this.currentStudent || !this.currentStudent.id) {
        Toast.fail('未获取到学生信息')
        return
      }

      const currentTabData = this.tabData[this.activeTab]

      // 如果是下拉刷新，重置所有状态
      if (this.refreshing) {
        currentTabData.orders = []
        currentTabData.page = 1
        currentTabData.hasMore = true
        currentTabData.finished = false
        currentTabData.loading = false
      }

      // 如果没有更多数据，直接返回
      if (!currentTabData.hasMore) {
        currentTabData.loading = false
        currentTabData.finished = true
        return
      }

      this.loading = true
      try {
        const params = {
          studentId: this.currentStudent.id,
          purchaseStatus: this.activeTab === 0 ? null : (this.activeTab === 1 ? 1 : 3),
          current: currentTabData.page,
          size: 10
        }

        const response = await api.getPurchaseList(params)
        console.log('API响应:', response)
        if (response && response.data && response.data.code === 200) {
          const ordersData = response.data.rows || []
          console.log('获取到订单数据:', ordersData)

          const orders = ordersData.map(item => ({
            id: item.id,
            productName: item.itemName,
            productImage: item.itemImg,
            points: item.totalAmount,
            orderNo: item.id,
            studentName: item.studentName,
            createTime: item.createTime || item.purchaseTime,
            status: item.purchaseStatus,
            purchaseMethod: item.purchaseMethod,
            description: `数量: ${item.purchaseQuantity}, 总价: ${item.totalAmount}`
          }))

          // 合并数据
          if (currentTabData.page === 1) {
            currentTabData.orders = orders
          } else {
            currentTabData.orders = [...currentTabData.orders, ...orders]
          }

          // 判断是否还有更多数据
          const total = response.data.total || 0
          const currentTotal = currentTabData.orders.length
          currentTabData.hasMore = currentTotal < total
          currentTabData.finished = !currentTabData.hasMore

          console.log('处理后订单数据:', orders)
          console.log('总记录数:', total, '当前记录数:', currentTotal, '是否有更多数据:', currentTabData.hasMore)
        } else {
          console.log('没有获取到订单数据或响应格式错误')
          currentTabData.orders = []
          currentTabData.hasMore = false
          currentTabData.finished = true
        }
      } catch (error) {
        console.error('获取购买历史失败:', error)
        Toast.fail('获取购买历史失败')
        currentTabData.orders = []
        currentTabData.hasMore = false
        currentTabData.finished = true
      } finally {
        this.loading = false
        currentTabData.loading = false

        // 如果是下拉刷新，重置刷新状态
        if (this.refreshing) {
          this.refreshing = false
        }
      }
    },
    getStatusClass(status) {
      switch (status) {
        case "1": // 待领取
          return 'pending'
        case "2": // 已取消
          return 'cancelled'
        case "3": // 已领取
          return 'completed'
        case "4": // 领取失败
          return 'failed'
        default:
          return 'default'
      }
    },
    getStatusText(status) {
      switch (status) {
        case "1": // 待领取
          return '待领取'
        case "2": // 已取消
          return '已取消'
        case "3": // 已领取
          return '已领取'
        case "4": // 领取失败
          return '领取失败'
        default:
          return '未知状态'
      }
    },

    // 获取购买方式文本
    getPurchaseMethodText(purchaseMethod) {
      console.log('purchaseMethod:', purchaseMethod)
      switch (String(purchaseMethod)) {
        case '1':
          return '积分购买'
        case '2':
          return '现金购买'
        default:
          return '未知方式'
      }
    },

    // 格式化金额显示
    formatAmount(amount) {
      if (!amount && amount !== 0) return '0.00'
      const num = parseFloat(amount)
      if (isNaN(num)) return '0.00'
      return num.toFixed(2)
    },
    showOrderDetail(order) {
      console.log('showOrderDetail order:', order)
      console.log('order.purchaseMethod:', order.purchaseMethod)
      this.currentOrder = { ...order }
      this.showDetail = true
    },
    async confirmReceipt(order) {
      try {
        const response = await api.confirmReceipt({ purchaseId: order.id })
        if (response && response.data.success) {
          Toast.success('确认收货成功')
          order.status = "3"
          this.showDetail = false
          // 重新加载购买历史数据
          this.loadPurchaseHistory()
        } else {
          Toast.fail('确认收货失败')
        }
      } catch (error) {
        console.error('确认收货失败:', error)
        Toast.fail('确认收货失败')
      }
    },
    cancelExchange(order) {
      // 显示退货原因输入弹窗
      this.selectedOrderId = order.id
      this.returnReason = ''
      this.showCancelDialog = true
    },

    // 提交取消兑换请求
    async submitCancelExchange() {
      if (!this.returnReason.trim()) {
        Toast.fail('请输入取消兑换的原因')
        return
      }

      try {
        const params = {
          purchaseId: this.selectedOrderId,
          returnReason: this.returnReason.trim()
        }

        console.log('取消兑换请求参数:', params)
        const response = await api.cancelExchange(params)
        console.log('取消兑换API响应:', response)

        if (response && response.data.success) {
          Toast.success('取消兑换成功')
          console.log('取消兑换成功，开始刷新列表...')

          // 重置所有标签页的分页状态
          Object.keys(this.tabData).forEach(tab => {
            this.tabData[tab].page = 1
            this.tabData[tab].orders = []
            this.tabData[tab].hasMore = true
            this.tabData[tab].loading = false
            this.tabData[tab].finished = false
          })

          // 重新加载当前标签页的数据
          this.loadPurchaseHistory()

          this.showDetail = false
          this.showCancelDialog = false
          this.returnReason = ''
          this.selectedOrderId = null
        } else {
          const errorMsg = response?.data?.message || '取消兑换失败'
          console.log('取消兑换失败:', errorMsg)
          Toast.fail(errorMsg)
        }
      } catch (error) {
        console.error('取消兑换失败:', error)
        Toast.fail('取消兑换失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .purchase-history {
    width: 100%;
    height: 100%;
    background: #f6f8fc;

    .history-head {
      width: 100%;
      background: #fff;
    }

    .history-content {
      height: calc(100% - 44px);
      width: 100%;
      overflow: hidden;
      padding: 15px 0;

      .order-list {
        box-sizing: border-box;

        .order-item:first-child {
          margin-top: 0;
        }

        .order-item {
          width: calc(100% - 30px);
          margin: 0 auto 15px;
          background: white;
          border-radius: 8px;
          padding: 15px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

          .order-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 12px;
            padding-bottom: 10px;
            border-bottom: 1px solid #f0f0f0;

            .order-time {
              font-size: 12px;
              color: #999;
            }

            .order-status {
              font-size: 12px;
              padding: 2px 8px;
              border-radius: 12px;

              &.pending {
                background: #fff7e6;
                color: #fa8c16;
              }

              &.cancelled {
                background: #f5f5f5;
                color: #999;
              }

              &.completed {
                background: #f6ffed;
                color: #52c41a;
              }

              &.failed {
                background: #fff2f0;
                color: #ff4d4f;
              }

              &.default {
                background: #f5f5f5;
                color: #666;
              }
            }
          }

          .order-info {
            display: flex;
            align-items: center;

            .product-image {
              width: 50px;
              height: 50px;
              border-radius: 6px;
              overflow: hidden;
              margin-right: 12px;

              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }

              .product-details {
                flex: 1;

                .product-name {
                  font-size: 14px;
                  font-weight: bold;
                  color: #333;
                  margin-bottom: 4px;
                }

                .product-points {
                  font-size: 12px;
                  color: #ff6b6b;
                  margin-bottom: 2px;
                }

                .order-number {
                  font-size: 11px;
                  color: #999;
                }

                .purchase-method {
                  font-size: 11px;
                  color: #1890ff;
                  font-weight: 500;
                  margin-top: 2px;
                }
              }
          }

          .order-actions {
            margin-top: 12px;
            text-align: right;
          }
        }
      }

      .nodata {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  // 订单详情弹窗样式
  .order-detail {
    height: 100%;
    display: flex;
    flex-direction: column;

    .detail-header {
      padding: 20px 16px 16px;
      text-align: center;
      border-bottom: 1px solid #f0f0f0;

      h3 {
        margin: 0;
        font-size: 18px;
        font-weight: bold;
        color: #333;
      }
    }

    .detail-content {
      flex: 1;
      padding: 16px;
      overflow-y: auto;

      .detail-section {
        margin-bottom: 20px;
        background: white;
        border-radius: 8px;
        padding: 16px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);

        .section-title {
          font-size: 16px;
          font-weight: bold;
          color: #333;
          margin-bottom: 12px;
          padding-bottom: 8px;
          border-bottom: 1px solid #f0f0f0;
        }

        .product-info {
          display: flex;
          align-items: center;

          .product-image {
            width: 60px;
            height: 60px;
            border-radius: 8px;
            overflow: hidden;
            margin-right: 12px;

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
          }

          .product-details {
            flex: 1;

            .product-name {
              font-size: 16px;
              font-weight: bold;
              color: #333;
              margin-bottom: 6px;
            }

            .product-points {
              font-size: 14px;
              color: #ff6b6b;
              font-weight: bold;
            }
          }
        }

        .order-info-list {
          .info-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid #f8f8f8;

            &:last-child {
              border-bottom: none;
            }

            .label {
              font-size: 14px;
              color: #666;
            }

            .value {
              font-size: 14px;
              color: #333;
              font-weight: 500;

              &.pending {
                color: #fa8c16;
                font-weight: bold;
              }

              &.cancelled {
                color: #999;
                font-weight: bold;
              }

              &.completed {
                color: #52c41a;
                font-weight: bold;
              }

              &.failed {
                color: #ff4d4f;
                font-weight: bold;
              }

              &.default {
                color: #666;
                font-weight: bold;
              }
            }
          }
        }

        .product-description {
          font-size: 14px;
          color: #666;
          line-height: 1.5;
          padding: 8px 0;
        }
      }
    }

    .detail-actions {
      padding: 16px;
      border-top: 1px solid #f0f0f0;
      background: white;
    }
  }

</style>
<style lang="scss">
  .purchase-history {
    .van-pull-refresh {
      height: 100%;
    }
    .van-list {
      height: 100%;
      overflow: scroll;
      -webkit-overflow-scrolling: touch;
    }
  }
</style>
